<?php
/**
 * Created by PhpStorm.
 * User: caoguangyang
 * Date: 2023-07-08
 * Time: 9:45
 */

namespace App\Http\Controllers\Wx;

use App\CodeResponse;
use App\Inputs\OrderSubmitInput;
use App\Jobs\OrderUnpaidTimeEndJob;
use App\Services\Order\CartServices;
use App\Services\Order\OrderServices;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class OrderController extends WxController
{
    /**
     * 提交订单
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function submit() {
        $input = OrderSubmitInput::new();

        $lockKey = sprintf("order_submit_%s_%s", $this->userId(), md5(serialize($input)));
        $lock = Cache::lock($lockKey, 5);
        if (!$lock->get()) {
            return $this->fail(CodeResponse::FAIL, "请勿重复请求");
        }
        $order = DB::transaction(function () use ($input) {
            return OrderServices::getInstance()->submit($this->userId(), $input);
        });
        return $this->success([
           'orderId' => $order->id,
           'grouponLikeId' => $input->grouponLinkId ?? 0
        ]);
    }

    /**
     * 用户取消订单
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\BusinessException
     */
    public function cancel() {
        $orderId = $this->verifyId('orderId');
        OrderServices::getInstance()->userCancel($this->userId(), $orderId);
        return $this->success();
    }

    /**
     * 申请退款
     * @return JsonResponse
     * @throws BusinessException
     * @throws Throwable
     */
    public function refund()
    {
        $orderId = $this->verifyId('orderId');
        OrderServices::getInstance()->refund($this->userId(), $orderId);
        return $this->success();
    }

    /**
     * 确认收货
     * @return JsonResponse
     * @throws BusinessException
     * @throws Throwable
     */
    public function confirm()
    {
        $orderId = $this->verifyId('orderId');
        OrderServices::getInstance()->confirm($this->userId(), $orderId);
        return $this->success();
    }

    public function delete() {
        $orderId = $this->verifyId('orderId');
        OrderServices::getInstance()->delete($this->userId(), $orderId);
        return $this->success();
    }
}